﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Data;

public partial class companypart_HistoryOfCheckings : System.Web.UI.Page
{
    int arrives;
    int noarrives;
    public  string GetUserID ()
    {
        return Session["user"].ToString().Split(',')[1];
    }
    protected void Page_Load(object sender, EventArgs e)
    {
      
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["company_product"] != null)
            {


                SqlDataSource1.SelectParameters["mysub"].DefaultValue = Request.QueryString["company_product"];
                GridView1.DataBind();
                ViewState["myid"] = Request.QueryString["company_product"];
                //adjust();
                main.Visible = false;
                details.Visible = true;
            }

            ViewState["filter"] = "";
            ViewState["from"] = "";
            
            if (getPostBackControlName() == "GridView1")
        if (!string.IsNullOrEmpty(ViewState["filter"].ToString()))
        {
            SqlDataSource1.SelectCommand += ViewState["filter"].ToString();
        }
           
            
        }
        DropDownList1.Items[1].Value = GetUserID();
        

    }
    private string getPostBackControlName()
    {

        Control control = null;

        //first we will check the "__EVENTTARGET" because if post back made by       the controls

        //which used "_doPostBack" function also available in Request.Form collection.

        string ctrlname = Page.Request.Params["__EVENTTARGET"];

        if (ctrlname != null && ctrlname != String.Empty)
        {

            control = Page.FindControl(ctrlname);

        }

        // if __EVENTTARGET is null, the control is a button type and we need to

        // iterate over the form collection to find it

        else
        {

            string ctrlStr = String.Empty;

            Control c = null;

            foreach (string ctl in Page.Request.Form)
            {

                //handle ImageButton they having an additional "quasi-property" in their Id which identifies

                //mouse x and y coordinates

                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {

                    ctrlStr = ctl.Substring(0, ctl.Length - 2);

                    c = Page.FindControl(ctrlStr);

                }

                else
                {

                    c = Page.FindControl(ctl);

                }

                if (c is System.Web.UI.WebControls.Button ||

                         c is System.Web.UI.WebControls.ImageButton)
                {

                    control = c;

                    break;

                }

            }

        }

        if (control != null)
            return control.ID;
        else
            return "";



    }
    protected override void InitializeCulture()
    {
        if (Session["CurrentCulture"] != null)
        {
            string lang = Session["CurrentCulture"].ToString();
            if (lang != null && lang != "")
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
                Thread.CurrentThread.CurrentCulture.DateTimeFormat = new CultureInfo("en-US", false).DateTimeFormat;
                // Thread.CurrentThread.CurrentCulture.Calendar=new  System.Globalization.GregorianCalendar();

            }
        }
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Attributes.Add("onmouseover", "this.Mystyle=this.style.backgroundColor;this.style.backgroundColor='#FFFFA8'");

        //    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.Mystyle");
        //}
    }
    protected void save_Click(object sender, EventArgs e)
    { 
        string filter="";
        if ((DatePicker1.SelectedDate.Year.ToString() != "1") && (DatePicker2.SelectedDate.Year.ToString() != "1")) //&& (RadioButtonList1.SelectedValue != null))
        {
            string froms = DatePicker1.SelectedDate.ToString("yyyy-MM-dd");
            ViewState["from"] = froms;
            filter=" and issuedate between Cast('" + froms + "' AS datetime) and Cast('" + DatePicker2.SelectedDate.ToString("yyyy-MM-dd")+"' AS datetime)";
           
        }
        if (DropDownList1.SelectedValue == "0")
        {
            filter += "and u.id is null ";
        }
        else
        {
            filter += "and u.id=" + DropDownList1.SelectedValue;
        }
        if(RadioButtonList1.SelectedValue!="")
        {
            filter+=" and delivered=" + RadioButtonList1.SelectedValue;
           // SqlDataSource1.SelectCommand += 
        
        }
        ViewState["filter"] = filter;
        SqlDataSource1.SelectCommand += filter;
        
        
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    double price = double.Parse(((Label)e.Row.FindControl("price")).Text);
        //    int n = int.Parse(((Label)e.Row.FindControl("no")).Text);
        //    if (bool.Parse(((Label)e.Row.FindControl("del")).Text))
        //    {
        //        arrives+=n;
        //        arriveprices += price*n;
        //    }
        //    else
        //    {
        //        noarrives += n;
        //        noarriveprices += price*n;
        //    }

        //    arrive.Text = arrives.ToString();
        //    arriveprice.Text = arriveprices.ToString();
        //    noarrive.Text = noarrives.ToString();
        //    noarriveprice.Text = noarriveprices.ToString();
              
        //}
    }
    public void adjust()
    {

        DataSet ds = DB.getproc("getstats", "@id," + ViewState["myid"].ToString());
        DataRow dr ;
        DataRow dr2;
        if (ds.Tables[0].Rows.Count == 2)
        {
            dr = ds.Tables[0].Rows[0];
            noarrive.Text = dr["received"].ToString();
            //noarriveprice.Text = dr["total"].ToString();

            dr2 = ds.Tables[0].Rows[1];
            arrive.Text = dr2["received"].ToString();
            //arriveprice.Text = dr2["total"].ToString();
        }
        if((ds.Tables[0].Rows.Count ==1))
        {
           bool delivered = Convert.ToBoolean( ds.Tables[0].Rows[0]["delivered"]);
           if(delivered)
           {
               dr = ds.Tables[0].Rows[0];
               noarrive.Text = "0";
               //noarriveprice.Text = "0";

               arrive.Text = dr["received"].ToString();
               //arriveprice.Text = dr["total"].ToString();
           }
           else
           {
               dr = ds.Tables[0].Rows[0];
               noarrive.Text = dr["received"].ToString();
               //noarriveprice.Text = dr["total"].ToString();


               arrive.Text = "0";
               //arriveprice.Text = "0";
           }
           
        }
        
    }
    protected void ints_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/followerpart/InternalHistory.aspx?company_product=" + ViewState["myid"].ToString());
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        if(GridView1.Rows.Count>0)
        {
            GridViewRow grv = GridView1.Rows[1];
            string dd = ((HiddenField)grv.FindControl("proid")).Value;
            if(ViewState["from"].ToString()=="")
              ViewState["from"]  = DateTime.Parse(((HiddenField)grv.FindControl("start")).Value).ToShortDateString();
            
           // string[] st = new string[] { "where" };
            string vv =  " where t.id=" + ViewState["myid"].ToString()+ ViewState["filter"].ToString() ; //Request.QueryString["company_product"];//SqlDataSource1.SelectCommand.ToString().Split(st,StringSplitOptions.None)[0];
            CheckingHistory ch = DB.getCheckHistory(vv,dd);
            Session["thats"] = ch;
            
            //string myval = arrive.Text + "," + arriveprice.Text + "," + noarrive.Text + "," + noarriveprice.Text;
            string redirect = "~/reps2.aspx?rep=" + "Checkings" +/* "&params=" + myval +*/ "&from=" + ViewState["from"].ToString();
            Response.Redirect(redirect);

        }

    }

    protected void currentsubs_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (currentsubs.SelectedValue != "0")
        {
            SqlDataSource1.SelectParameters["mysub"].DefaultValue = currentsubs.SelectedValue;
            GridView1.DataBind();
            ViewState["myid"] = currentsubs.SelectedValue;
            //adjust();
            details.Visible = true;
        }
    }
    protected void LinkButton1_Click1(object sender, EventArgs e)
    {
        Response.Redirect("~/companypart/InternalHistory.aspx?company_product=" + ViewState["myid"].ToString());
        
    }

    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        DataTable dt = ((DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty)).Table;
        string sumarrive = dt.Compute("sum(receivedcopy)", "checked = 1 and delivered =1").ToString();
        arrive.Text = sumarrive == "" ? "0" : sumarrive;
        string sumnotchecked = dt.Compute("sum(copyno)", "checked = 0").ToString();
        NotCheckedItems.Text = sumnotchecked==""?"0":sumnotchecked;

        int a =0;int b=0;
        string sumallchecked = dt.Compute("sum(copyno)", "checked = 1").ToString();
        int.TryParse(sumallchecked,out a);
        int.TryParse(sumarrive,out b);
        noarrive.Text = (a - b).ToString();
    }
}
